import { createApp } from 'vue'
import App from './App.vue'
import './registerServiceWorker'
import router from './router'
import 'lib-flexible/flexible'
import Antd from 'ant-design-vue'
import 'ant-design-vue/dist/antd.less'
import * as Icons from '@ant-design/icons-vue'

const app = createApp(App)
const icons: any = Icons
for (const i in icons) {
  app.component(i, icons[i])
}
// 获取原型
const prototype = app.config.globalProperties

// 绑定参数
prototype.author = 'orgin test'

app.use(router).use(Antd).mount('#app')

// 全局指定
app.directive('resize', {
  beforeMount (el: any, binding: any):void {
    let width = ''
    function isReize () {
      const style = window.getComputedStyle(el)
      if (width !== style.width) {
        binding.value()
      }
      width = style.width
    }
    el.__vueSetInterval__ = setInterval(isReize, 500)
  },
  unmounted (el: any):void {
    clearInterval(el.__vueSetInterval__)
  }
})

// 全局滚动事件监听
app.directive('scroll', {
  mounted (el: any, binding: any):void {
    const f = function (evt:any) {
      if (binding.value(evt, el)) {
        el.removeEventListener('scroll', f)
      }
    }
    el.addEventListener('scroll', f, true)
  }
})

let registerRouteFresh = true
router.beforeEach((to, from, next) => {
  const data = [
    {
      path: '/demo4/child',
      component: 'demoChild',
      redirect: '',
      children: [],
      meta: {
        title: 'demo4 child'
      },
      name: 'demo4Child',
      id: 10
    }, {
      path: '/demo4',
      component: 'demo4',
      redirect: '',
      children: [],
      meta: {
        title: 'demo4'
      },
      name: 'demo4',
      id: 11
    }
  ]
  const arr:any = []
  data.filter((value) => {
    const child:any = []
    if (value.children && value.children.length > 0) {
      // value.children.filter((val, i) => {
      //   let component = ''
      //   if (val.component.indexOf('layouts') >= 0) {
      //     component = 'components/' + val.component
      //   } else {
      //     component = 'views/' + val.component
      //   }
      //   child.push({
      //     name: val.name,
      //     path: val.path,
      //     // component: resolve => require(['@/' + component + '.vue'], resolve)
      //     component: () => import(`@/${component}.vue`)
      //   })
      // })
    }
    let url = ''
    if (value.component.indexOf('layouts') >= 0) {
      url = 'components/' + value.component
    } else {
      url = 'views/' + value.component
    }
    arr.push({
      name: value.name,
      redirect: value.redirect,
      path: value.path,
      // path: '/:catchAll(.*)',
      component: () => import(`@/${url}.vue`),
      children: child
    })
  })
  if (registerRouteFresh) {
    console.log(arr)
    arr.forEach((value:any) => {
      router.addRoute(value)
    })
    next({ ...to, replace: true })
    registerRouteFresh = false
    console.log('arr', arr)
  } else {
    next()
  }
})
